import { useUserStore } from '@/stores/modules/user'
import request from '@/utils/request2.js'
import { TIME_STAMP, TOKEN_TIMEOUT_VALUE } from '@/constant'
import { setItem, getItem } from '@/utils/storage'
const APPID = 'ww302956c69e4ee7fc'
const REDIRECT_URI = 'http%3A%2F%2Fwx.hujinhu.cn/pc'
const AGENTID = '1000004'
const wxURL = 'http://wx.hujinhu.cn'
const userStore = useUserStore()
const getAuth = (appName) => {
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_privateinfo&state=${appName}&agentid=${AGENTID}#wechat_redirect`
}

export const getCode = async () => {
  if(isCheckTimeout()){
    userStore.token = ''
  }
  if (userStore.token) {
    return
  }
  const search = window.location.search
  if (search.includes('code')) {
    console.log(search)
    let code = search.split('&')[0].split('=')[1]
    let state = search.split('&')[1].split('=')[1]
    fetch(`${wxURL}/api/wx/callback?code=${code}`)
      .then((response) => response.json())
      .then((res) => {
        // alert(JSON.stringify(res.data))
        setTimeStamp()
        userStore.token = res.data.token
        window.location.href = `http://wx.hujinhu.cn/pc?appName=${state}`
      })
      .catch((err) => {})
  } else {
    let appName = ''
    if (search.includes('byhb')) {
      appName = 'byhb'
    } else {
      appName = 'xfpc'
    }
    getAuth(appName)
  }
}

export const getCommunication = async () => {
  // if (userStore.token) {
  console.log('ww', ww)
  try {
    const ticket = await request({
      url: '/common/js_ticket',
      method: 'GET'
    })
    ww.register({
      corpId: APPID,
      jsApiList: ['selectEnterpriseContact'],
      getConfigSignature() {
        return ww.getSignature(ticket)
      }
    })
  } catch (error) {
    console.log(error)
  }
  // }
}

/**
 * 获取时间戳
 */
export function getTimeStamp() {
  return getItem(TIME_STAMP)
}
/**
 * 设置时间戳
 */
export function setTimeStamp() {
  setItem(TIME_STAMP, Date.now())
}
/**
 * 是否超时
 */
export function isCheckTimeout() {
  // 当前时间戳
  var currentTime = Date.now()
  // 缓存时间戳
  var timeStamp = getTimeStamp()
  return currentTime - timeStamp > TOKEN_TIMEOUT_VALUE
}
